<template>
  <div id="invOrderOutDiv">
    <Breadcrumb content="出库管理" />
    <div class="bodyContent">
      <Splitpanes>
        <Pane size="50">
          <vxe-form :data="searchForm" class="searchform form-input-m">
            <vxe-form-item title="单据日期[起]">
              <template #default="{ data }">
                <el-date-picker v-model="data.documentDateBegin" :value-format="'YYYY-MM-DD HH:mm:ss'" type="datetime" placeholder="标本日期[起]" :shortcuts="shortcuts" />
              </template>
            </vxe-form-item>
            <vxe-form-item title="单据日期[止]">
              <template #default="{ data }">
                <el-date-picker v-model="data.documentDateEnd" :value-format="'YYYY-MM-DD HH:mm:ss'" type="datetime" placeholder="标本日期[止]" :shortcuts="shortcuts" />
              </template>
            </vxe-form-item>
            <vxe-form-item title="流转单号">
              <vxe-input v-model="searchForm.transferNo" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findInvOrderList" @keyup="keyupEnter" @search-click="findInvOrderList()"></vxe-input>
            </vxe-form-item>
            <vxe-form-item title="流转方式">
              <vxe-select v-model="searchForm.transferType" :filterable="true" @change="transferChangeEvent" clearable transfer>
                <vxe-option v-for="transfer in transTypeList" :key="transfer.id" :value="transfer.transferCode" :label="transfer.transferName"></vxe-option>
              </vxe-select>
            </vxe-form-item>
            <vxe-form-item title="单据状态">
              <vxe-select v-model="searchForm.orderStatus" :filterable="true" @change="orderStatusChangeEvent" clearable transfer>
                <vxe-option v-for="orderSObj in invOrderStatusList" :key="orderSObj.commonId" :value="orderSObj.code" :label="orderSObj.name"></vxe-option>
              </vxe-select>
            </vxe-form-item>
            <vxe-form-item>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-search" content="查询" :loading="tloading" @click="findInvOrderList"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-square-plus" content="新增" @click="addInvOrderDialog()"></vxe-button>
              <vxe-button type="text" class="button-blue" icon="vxe-icon-check" v-if="!isEmpty(sltTransType)&&sltTransType.isFinaState==1" content="财务验收" @click="orderFinanceCheck()"></vxe-button>
              <vxe-button type="text" icon="vxe-icon-delete" class="button-red" content="删除" @click="deleteInvReagent"></vxe-button>
            </vxe-form-item>
          </vxe-form>
          <div class="tableBoBox">
            <vxe-table ref="invOrderTableRef" class="mytable-scrollbar supplierTableClazz" border="inner" align="center" height="auto" :data="invOrderList" :loading="tloading" @current-change="invOrderRowClick" :row-config="{ isCurrent: true, isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
              <vxe-column type="checkbox" width="30"></vxe-column>
              <vxe-column field="orderStatus" title="状态" width="80">
                <template #default="{ row }">
                  <div class="justify-atart">
                    <span :class="getStatusClass(row)">
                      {{ formatCommon(invOrderStatusList, row.orderStatus) }}
                    </span>
                  </div>
                </template>
              </vxe-column>
              <vxe-column field="transferNo" title="流转单号" width="200">
                <template #default="{ row }">
                  <span>{{ row.transferNo }}</span>
                </template>
              </vxe-column>
              <vxe-column field="transferType" title="流转方式" width="80">
                <template #default="{ row }">
                  <span>
                    {{ formatTransType(transTypeList, row.transferType) }}
                  </span>
                </template>
              </vxe-column>
              <vxe-column field="receiveDeptNa" title="领用科室" width="200">
                <template #default="{ row }">
                  <span>{{ row.receiveDeptNa }}</span>
                </template>
              </vxe-column>
              <vxe-column field="documentDate" title="单据日期" width="150"> </vxe-column>
              <vxe-column field="storagePersonnel" title="领用人" width="100"></vxe-column>
              <vxe-column field="notifyPerson" title="确认人" width="100"></vxe-column>
              <vxe-column field="notifyDate" title="确认时间" width="100"></vxe-column>
              <vxe-column field="remake" title="备注" width="300">
                <template #default="{ row }">
                  <span>{{ row.remake }}</span>
                </template>
              </vxe-column>
              <vxe-column field="seq" title="顺序" width="50">
                <template #default="{ row }">
                  <span>{{ row.seq }}</span>
                </template>
              </vxe-column>
            </vxe-table>
          </div>
        </Pane>
        <Pane size="50">
          <Splitpanes horizontal class="horizontalLine">
            <Pane size="40">
              <vxe-toolbar perfect>
                <template #buttons>
                  <div class="toolbartitle">订单详情</div>
                  <div class="saveBtn">
                    <vxe-button type="text" class="button-blue" :loading="sloading" @click="saveOrderInfo('orderFormRef')" :disabled="!isEmpty(orderForm.id)&&orderForm.orderStatus!='5'" icon="vxe-icon-square-plus" content="保存"></vxe-button>
                    <vxe-button type="text" class="button-blue" icon="vxe-icon-check" content="确认" :disabled="isEmpty(orderForm.id)||orderForm.orderStatus !='5'" @click="checkOutStock()"></vxe-button>
                  </div>
                </template>
              </vxe-toolbar>
              <el-form ref="orderFormRef" :model="orderForm" label-width="100px" inline-message>
                <el-row>
                  <el-col :span="8"><el-form-item prop="transferType" label="流转方式">
                      <el-select v-model="orderForm.transferType" placeholder="请选择">
                        <el-option v-for="tranType in transTypeList" :key="tranType.id" :label="tranType.transferName" :value="tranType.transferCode" />
                      </el-select>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item prop="transferNo" label="制单编号">
                      <el-input type="text" v-model="orderForm.transferNo" placeholder="自动生成" disabled></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item prop="documentDate" label="制单日期">
                      <el-date-picker v-model="orderForm.documentDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item prop="receiveDeptNa" label="领用科室">
                      <VxePulldownSelectionWithNa style="width: 100%" :url="'/api/sys/findDepartmentListbyCurrentUserOrg'" @confirmClick="SelectRowClick" :tableColumn="[
                { field: 'code', title: '编码' },
                { field: 'name', title: '名称' }
              ]" :aimKeys="[
                { aimKey: 'receiveDept', rowKey: 'code' },
                { aimKey: 'receiveDeptNa', rowKey: 'name' }
              ]" :displayTexts="['receiveDeptNa']" :displayTextObj="orderForm.receiveDeptNa ? orderForm.receiveDeptNa : ''" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item prop="receiveDate" label="领用日期">
                      <el-date-picker v-model="orderForm.receiveDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item prop="invoiceNumber" label="发票号码">
                      <el-input type="text" v-model="orderForm.invoiceNumber" placeholder="请输入发票号码"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item prop="storagePersonnel" label="领用人">
                      <el-input type="text" v-model="orderForm.storagePersonnel" placeholder="请输入领用人"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item prop="notifyPerson" label="出库人">
                      <el-input type="text" v-model="orderForm.notifyPerson" placeholder="请输入出库人"></el-input>
                    </el-form-item>
                  </el-col>
                  <el-col :span="8">
                    <el-form-item prop="notifyDate" label="出库时间">
                      <el-date-picker v-model="orderForm.notifyDate" type="datetime" value-format="YYYY-MM-DD HH:mm:ss" placeholder="选择日期" />
                    </el-form-item>
                  </el-col>
                  <el-col :span="24">
                    <el-form-item prop="remake" label="备注">
                      <el-input type="textarea" v-model="orderForm.remake" placeholder="请输入说明"></el-input>
                    </el-form-item>
                  </el-col>
                </el-row>
              </el-form>
            </Pane>
            <Pane size="60">
              <vxe-toolbar perfect>
                <template #buttons>
                  <div class="smallToolTitle">出库明细</div>
                  <vxe-button @click="checkReagentDialog" :disabled="!isEmpty(orderForm.id)&&orderForm.orderStatus!='5'" type="text" class="button-blue margin-left-xs" icon="vxe-icon-square-plus">增加物品</vxe-button>
                </template>
              </vxe-toolbar>
              <div class="tableBox">
                <vxe-table ref="reagentTableRef" :data="orderForm.reagentList" :loading="iloading" class="mytable-scrollbar" border="inner" align="center" :column-config="{ resizable: true }" :edit-config="{ trigger: 'click', mode: 'row', showStatus: true }" resizable show-overflow keep-source>
                  <vxe-column title="操作" align="center" fixed="left" width="50">
                    <template #default="{ row }">
                      <vxe-button type="text" status="danger" icon="vxe-icon-delete" :disabled="!isEmpty(orderForm.id)&&orderForm.orderStatus!='5'" circle @click.native="deleteReagent(row)"></vxe-button>
                    </template>
                  </vxe-column>
                  <vxe-column field="reaNo" title="编码"> </vxe-column>
                  <vxe-column field="reaNa" title="名称"> </vxe-column>
                  <vxe-column field="specModel" title="规格型号"> </vxe-column>
                  <vxe-column field="batchNum" title="批号"></vxe-column>
                  <vxe-column field="amount" title="目标库存"></vxe-column>
                  <vxe-column field="applyNum" title="申请数量" :edit-render="{}">
                    <template #default="{ row }">
                      <div>{{ row.applyNum }}</div>
                    </template>
                    <template #edit="{ row }">
                      <vxe-input v-model="row.applyNum" type="text" @blur="pdNum(row)" clearable></vxe-input>
                    </template>
                  </vxe-column>
                  <vxe-column field="unit" title="单位"></vxe-column>
                  <vxe-column field="produceDate" title="生产日期"></vxe-column>
                  <vxe-column field="expiryDate" title="失效日期"></vxe-column>
                  <vxe-column field="uniqueCode" title="唯一编码"></vxe-column>
                </vxe-table>
              </div>
            </Pane>
          </Splitpanes>
        </Pane>
      </Splitpanes>
    </div>
  </div>
  <el-dialog title="选择商品" v-model="isStockVisiable" :modal-append-to-body="false" :close-on-click-modal="false" width="1000px">

    <template #title>
      <span class="text-bold">增加物品</span>
    </template>
    <template #default>

      <vxe-form :data="searchStockForm" class="searchform form-input-m">
        <vxe-form-item title="快速查询">
          <vxe-input style="width: 180px" v-model="searchStockForm.searchValue" type="search" clearable class="vxeInputSearch" placeholder="关键字查询" @clear="findReagentStockList" @keyup="keyupStockEnter" @search-click="findReagentStockList()" transfer></vxe-input>
        </vxe-form-item>
        <vxe-form-item title="仓库">
          <el-select v-model="searchStockForm.storeCode" placeholder="请选择仓库" ref="selectOrgRef" style="width:180px;" clearable @clear="clearStoreCode">
            <el-option hidden :value="searchStockForm.storeCode ? searchStockForm.storeCode : ''" :label="searchStockForm.storeName"></el-option>
            <el-tree filterable :data="invStoreList" :props="defaultProps" :expand-on-click-node="false" :default-expand-all="true" @node-click="handleTypeNodeClick" highlight-current ref="orgTreeRef" node-key="faultTypeCode" class="tools-tree"></el-tree>
          </el-select>
        </vxe-form-item>

        <vxe-form-item>
          <vxe-button type="text" class="button-blue" icon="vxe-icon-search" content="查询" :loading="tloading" @click="findReagentStockList"></vxe-button>
        </vxe-form-item>
      </vxe-form>

      <div class="tableBody">
        <vxe-table ref="stockTableRef" class="mytable-scrollbar dialogTable" border height="520px" align="center" :data="reagentStockList" :loading="ploading" :row-config="{ keyField: 'id', isHover: true }" :column-config="{ resizable: true }" resizable show-overflow keep-source>
          <vxe-column title="序号" width="80">
            <template #default="{ row, rowIndex, column }">
              <span>{{ rowIndex + 1 }}</span>
            </template>
          </vxe-column>
          <vxe-column type="checkbox" width="30px"></vxe-column>
          <vxe-column field="reaNo" title="编码"></vxe-column>
          <vxe-column field="reaNa" title="商品名称"></vxe-column>
          <vxe-column field="specModel" title="规格型号"></vxe-column>
          <vxe-column field="batchNum" title="批号"></vxe-column>
          <vxe-column field="quantity" title="数量"></vxe-column>
          <vxe-column field="unit" title="单位"></vxe-column>
          <vxe-column field="price" title="单价"></vxe-column>
          <vxe-column field="produceDate" title="生产日期"></vxe-column>
          <vxe-column field="expiryDate" title="失效日期"></vxe-column>
          <vxe-column field="uniqueCode" title="唯一编码"></vxe-column>
          <vxe-column field="storeName" title="仓库"></vxe-column>
        </vxe-table>
      </div>
    </template>

    <template #footer>
      <vxe-button type="text" class="button-white margin-right" @click="cancelStockEvent">关闭</vxe-button>
      <vxe-button type="text" class="button-blue" @click="confirmStockEvent">确定</vxe-button>
    </template>
  </el-dialog>
</template>
<script setup lang="ts">
// 引入组件区 ==========
import { ref, reactive, getCurrentInstance, onMounted } from 'vue';
import Breadcrumb from '@/components/Breadcrumb.vue';
import moment from 'moment';
import { Splitpanes, Pane } from 'splitpanes';
import { formatDateTime, notifyMessage, notifyType } from '@/utils/common';
import { AppStore } from '@/stores/store';
import VxePulldownSelectionWithNa from '@/components/VxePulldownSelectionWithNa.vue';

import { VxeMessage, VxeNotifyType } from '@/utils/CommonMessage'; //提示框
import { isEmpty } from 'lodash';
import type { Length } from 'html2canvas/dist/types/css/types/length';
let { proxy }: any = getCurrentInstance();
let invOrderStatusList: any = reactive([]);
let transTypeList: any = reactive([]);
let invOrderList: any = reactive([]);
let tloading = ref(false); //刷新加载状态
let iloading = ref(false); //刷新加载状态
let sloading = ref(false);
let store = AppStore();
let defaultProps = {
  children: 'children',
  label: 'storeName'
};
let isStockVisiable = ref(false);
let reagentStockList: any = reactive([]); //弹框表格数据
let ploading = ref(false); //弹框表格数据加载状态
let searchStockForm = reactive({
  storeCode: !isEmpty(store.curInvStoreObj) && !isEmpty(store.curInvStoreObj.storeCode) ? store.curInvStoreObj.storeCode : '',
  storeName: !isEmpty(store.curInvStoreObj) && !isEmpty(store.curInvStoreObj.storeName) ? store.curInvStoreObj.storeName : '',
  searchValue: ''
});
let sltInvOrder: any = ref({});
let sltTransType: any = reactive({});
let invStoreList: any = reactive([]);

let orderForm: any = reactive({
  id: null,
  supplierCode: '',
  supplierName: '',
  tarStoreNa: '',
  tarStoreCode: '',
  invoiceNumber: '',
  invoiceDate: '',
  documentDate: formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss'),
  purOrderNumber: '',
  outOrderNumber: '',
  businessType: '',
  storagePersonnel: '',
  storageMark: '',
  notifyPerson: '',
  notifyDate: '',
  remake: '',
  receiveDept: '',
  receiveDeptNa: '',
  receiveDate: '',
  seq: null,
  reagentList: []
});
let searchForm = reactive({
  searchValue: '',
  transferNo: '',
  transferType: '',
  transferTypes: '',
  orderStatus: '',
  documentDateBegin: formatDateTime(new Date().setTime(new Date().getTime() - 3600 * 1000 * 24 * 7), 'yyyy-MM-dd 00:00:00'),
  documentDateEnd: formatDateTime(new Date(), 'yyyy-MM-dd 23:59:59')
});

const shortcuts = [
  {
    text: '今天',
    value: new Date()
  },
  {
    text: '昨天',
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 1);
      return date;
    }
  },
  {
    text: '一周前',
    value: () => {
      const date = new Date();
      date.setDate(date.getDate() - 7);
      return date;
    }
  }
];

// 页面加载时更新报告单元/字典
onMounted(async () => {
  if (!isEmpty(proxy.$route.query.orderStatus)) {
    searchForm.orderStatus = proxy.$route.query.orderStatus.toString();
  }

  findStoreManageTree();
  getDictItemsList(); //批量获取字典
  await findInvTransTypeList();
  await findInvOrderList();
});

function findStoreManageTree() {
  invStoreList.length = 0;

  const url = '/inv/storeManage/findStoreManageTree';
  proxy.$http
    .get(url)
    .then((res: any) => {
      if (res.status.code !== 1) {
        proxy.$alert(res.status.msg, '提示');
      } else {
        invStoreList.push(...res.data.invStoreTree);
      }
    })
    .catch((err: any) => {
      VxeMessage('获取机构失败', VxeNotifyType.error);
    });
}

//批量获取字典
async function getDictItemsList() {
  let dictTreeTypeCodes: any = ['invOrderStatus'];
  const codes = dictTreeTypeCodes.join(',');
  const url = '/api/sys/basDictDetail/findDictDetailListByDictCodes';
  const dictTreeTypeItems: any = await proxy.$http.get(url, { params: { code: codes } });
  const iosObj = dictTreeTypeItems.data.find((item: any) => item.code === 'invOrderStatus');
  invOrderStatusList.push(...iosObj.detailDataList);
}

async function findInvTransTypeList() {
  const url = '/inv/transfer/type/findInvTransferTypeList';
  await proxy.$http
    //注意此处的数据条数
    .get(url, { params: { businessType: '02', showFlag: true } })
    .then((res: any) => {
      if (res.status.code === 1) {
        transTypeList.push(...res.data);
        if (transTypeList.length > 0) {
          sltTransType = transTypeList[0];
          searchForm.transferType = transTypeList[0].transferCode;
          let codeList = transTypeList.map((m: any) => m.transferCode);
          searchForm.transferTypes = codeList.join(',');
        }
      }
    })
    .catch((err: any) => {
      // VxeMessage('获取机构列表失败',VxeNotifyType.error)
    });
}

// 回车查询
function keyupEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findInvOrderList();
  }
}

async function findInvOrderList() {
  tloading.value = true;
  invOrderList.length = 0; //放入数据前清空数据
  const url = '/inv/orderInfo/findOrderInfoList';
  await proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        searchValue: searchForm.searchValue,
        transferNo: searchForm.transferNo,
        orderStatus: searchForm.orderStatus,
        transferType: searchForm.transferType,
        transferTypes: searchForm.transferTypes,
        documentDateBegin: searchForm.documentDateBegin,
        documentDateEnd: searchForm.documentDateEnd
      }
    })
    .then((res: any) => {
      invOrderList.push(...res.data);
      if (invOrderList.length == 0) {
        sltInvOrder.value = {};
        clearOrderForm();
      } else {
        const kn = invOrderList.find((k: any) => k.id == sltInvOrder.value.id);
        if (isEmpty(kn)) {
          invOrderRowClick({ row: invOrderList[0] }); //默认选中第一条数据
        } else {
          invOrderRowClick({ row: kn }); //默认选中第一条数据
        }
      }

      tloading.value = false;
    })
    .catch((err: any) => {
      tloading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

// 点击质控品维护表格当前行触发右侧表单变化
function invOrderRowClick({ row }: any) {
  if (isEmpty(row)) {
    sltInvOrder.value = {};
    clearOrderForm();
  } else {
    (proxy.$refs.invOrderTableRef as any).setCurrentRow(row);
    sltInvOrder.value = row;
    //setOrderForm(row);
    findInvOrderInfoById();
  }
}
//获取修改所有页面信息
function findInvOrderInfoById() {
  iloading.value = true;
  const url = '/inv/orderInfo/findOrderInfoByAllot';
  proxy.$http
    .get(url, { params: { orderInfoId: sltInvOrder.value.id } })
    .then((res: any) => {
      if (res.status.code !== 1) {
        iloading.value = false;
        notifyMessage(res.status.msg, notifyType.warning, proxy);
      } else {
        iloading.value = false;
        setOrderForm(res.data);
      }
    })
    .catch((err) => {
      iloading.value = false;
      proxy.$alert(err, '提示');
    });
}
// 清空表单
function clearOrderForm() {
  orderForm.id = null;
  orderForm.supplierCode = '';
  orderForm.supplierName = '';
  orderForm.tarStoreNa = '';
  orderForm.tarStoreCode = '';
  orderForm.invoiceNumber = '';
  orderForm.invoiceDate = '';
  orderForm.documentDate = formatDateTime(new Date(), 'yyyy-MM-dd hh:mm:ss');
  orderForm.receiveDept = '';
  orderForm.receiveDeptNa = '';
  orderForm.receiveDate = '';
  orderForm.purOrderNumber = '';
  orderForm.outOrderNumber = '';
  orderForm.businessType = '';
  orderForm.storagePersonnel = '';
  orderForm.storageMark = '';
  orderForm.notifyPerson = '';
  orderForm.notifyDate = '';
  orderForm.remake = '';
  orderForm.transferType = '';
  orderForm.seq = null;
  orderForm.transferType = searchForm.transferType;
  orderForm.transferNo = '';
  orderForm.reagentList = [];
}

function setOrderForm(row: any) {
  Object.assign(orderForm, row);
}

function orderStatusChangeEvent() {
  findInvOrderList();
}
function transferChangeEvent() {
  if (!isEmpty(searchForm.transferType)) {
    sltTransType = transTypeList.find((item: any) => searchForm.transferType == item.transferCode);
  } else {
    sltTransType = {};
  }
  findInvOrderList();
}
function deleteInvReagent() {
  const sltQcMaterials = (proxy.$refs.invOrderTableRef as any).getCheckboxRecords();
  if (!(sltQcMaterials.length > 0)) {
    VxeMessage('请勾选要删除的数据', VxeNotifyType.info);
  } else {
    let cantCheckList = sltQcMaterials.filter((x: any) => x.orderStatus != '5');
    if (cantCheckList.length > 0) {
      VxeMessage('请选择未提交的数据', VxeNotifyType.info);
    } else {
    proxy
      .$confirm('确定要删除当前勾选的数据？', '提示', {
        cancelButtonClass: 'cancel-button',
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
      .then(() => {
        const data = { invOrderInfoList: sltQcMaterials };
        const url = '/inv/orderInfo/batchDeleteInvOrderInfoList';
        proxy.$http
          .post(url, data)
          .then((res: any) => {
            findInvOrderList(); // 获取检验仪器表格数据
            VxeMessage(res.status.msg, VxeNotifyType.success);
          })
          .catch((err: any) => {
            VxeMessage(err, VxeNotifyType.error);
          });
      })
      .catch((err: any) => {
        // VxeMessage(err, VxeNotifyType.error);
      });
  }}
}

function checkOutStock() {
  proxy
    .$confirm('确定验收入库？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(() => {
      const url = '/inv/orderInfo/checkOutStock';
      proxy.$http
        .post(url, orderForm)
        .then((res: any) => {
          findInvOrderList(); // 获取检验仪器表格数据
          VxeMessage(res.status.msg, VxeNotifyType.success);
        })
        .catch((err: any) => {
          VxeMessage(err, VxeNotifyType.error);
        });
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}

function orderFinanceCheck() {
  const sltQcMaterials = (proxy.$refs.invOrderTableRef as any).getCheckboxRecords();
  if (!(sltQcMaterials.length > 0)) {
    VxeMessage('请勾选要财务验收的单据', VxeNotifyType.info);
  } else {
    let cantCheckList = sltQcMaterials.filter((x: any) => x.orderStatus != '10');
    if (cantCheckList.length > 0) {
      VxeMessage('请选择未财务验收的单据', VxeNotifyType.info);
    } else {
      proxy
        .$confirm('确定财务验收？', '提示', {
          cancelButtonClass: 'cancel-button',
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        })
        .then(() => {
          const data = { invOrderInfoList: sltQcMaterials };
          const url = '/inv/orderInfo/orderFinanceCheck';
          proxy.$http
            .post(url, data)
            .then((res: any) => {
              findInvOrderList(); // 获取检验仪器表格数据
              VxeMessage(res.status.msg, VxeNotifyType.success);
            })
            .catch((err: any) => {
              VxeMessage(err, VxeNotifyType.error);
            });
        })
        .catch((err: any) => {
          // VxeMessage(err, VxeNotifyType.error);
        });
    }
  }
}

function addInvOrderDialog() {
  (proxy.$refs.invOrderTableRef as any).clearCurrentRow();
  clearOrderForm();
  sltInvOrder.value = {};
}

function saveOrderInfo(formName: any) {
  let $el = proxy.$refs[formName];
  $el.validate((valid: any) => {
    if (!valid) {
      return false;
    }
    sloading.value = true;
    if (orderForm.id === null) {
      const url = '/inv/orderInfo/addOrderInfo';
      const supplier = {
        transferNo: orderForm.transferNo,
        transferType: orderForm.transferType,
        orderStatus: '5',
        supplierCode: orderForm.supplierCode,
        supplierName: orderForm.supplierCode,
        tarStoreNa: orderForm.tarStoreNa,
        tarStoreCode: orderForm.tarStoreCode,
        invoiceNumber: orderForm.invoiceNumber,
        invoiceDate: orderForm.invoiceDate,
        documentDate: orderForm.documentDate,
        purOrderNumber: orderForm.purOrderNumber,
        outOrderNumber: orderForm.outOrderNumber,
        businessType: orderForm.businessType,
        storagePersonnel: orderForm.storagePersonnel,
        storageMark: orderForm.storageMark,
        notifyPerson: orderForm.notifyPerson,
        notifyDate: orderForm.notifyDate,
        remake: orderForm.remake,
        receiveDept: orderForm.receiveDept,
        receiveDate: orderForm.receiveDate,
        seq: orderForm.seq,
        reagentList: orderForm.reagentList
      };
      proxy.$http
        .post(url, supplier)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('新增成功', VxeNotifyType.success);
            clearOrderForm();
            sltInvOrder.value.id = res.data.id;
            findInvOrderList();
          } else {
            VxeMessage('新增失败', VxeNotifyType.error);
          }
          sloading.value = false;
          //findQiIndexSqlOne();
        })
        .catch((err: any) => {
          sloading.value = false;
          console.log(err);
          VxeMessage('新增失败', VxeNotifyType.error);
        });
    } else {
      // 修改用户
      const url = '/inv/orderInfo/editOrderInfo';

      const supplier = {
        id: orderForm.id,
        transferNo: orderForm.transferNo,
        transferType: orderForm.transferType,
        orderStatus: orderForm.orderStatus,
        supplierCode: orderForm.supplierCode,
        supplierName: orderForm.supplierCode,
        tarStoreNa: orderForm.tarStoreNa,
        tarStoreCode: orderForm.tarStoreCode,
        invoiceNumber: orderForm.invoiceNumber,
        invoiceDate: orderForm.invoiceDate,
        documentDate: orderForm.documentDate,
        purOrderNumber: orderForm.purOrderNumber,
        outOrderNumber: orderForm.outOrderNumber,
        businessType: orderForm.businessType,
        storagePersonnel: orderForm.storagePersonnel,
        storageMark: orderForm.storageMark,
        notifyPerson: orderForm.notifyPerson,
        notifyDate: orderForm.notifyDate,
        remake: orderForm.remake,
        receiveDept: orderForm.receiveDept,
        receiveDate: orderForm.receiveDate,
        seq: orderForm.seq,
        reagentList: orderForm.reagentList
      };
      proxy.$http
        .post(url, supplier)
        .then((res: any) => {
          if (res.status.code === 1) {
            VxeMessage('修改成功', VxeNotifyType.success);
            clearOrderForm();
            sltInvOrder.value.id = res.data.id;
            findInvOrderList();
          } else {
            VxeMessage('修改失败', VxeNotifyType.error);
          }
          sloading.value = false;
        })
        .catch((err: any) => {
          sloading.value = false;
          VxeMessage('修改失败', VxeNotifyType.error);
        });
    }
  });
}

function checkReagentDialog() {
  findReagentStockList();
  isStockVisiable.value = true;
}

function keyupStockEnter(e: any) {
  if (e.$event.code == 'Enter') {
    findReagentStockList();
  }
}

function findReagentStockList() {
  ploading.value = true;
  reagentStockList.length = 0; //放入数据前清空数据
  const url = '/inv/invReagentStock/findReagentStockList';
  proxy.$http
    //注意此处的数据条数
    .get(url, {
      params: {
        searchValue: searchStockForm.searchValue,
        storeCode: searchStockForm.storeCode,
        query0Flag: true
      }
    })
    .then((res: any) => {
      reagentStockList.push(...res.data);

      ploading.value = false;
    })
    .catch((err: any) => {
      ploading.value = false;
      // VxeMessage('获取获取当前字典的规则列表失败',VxeNotifyType.error)
    });
}

async function confirmStockEvent() {
  const selectRows = (proxy.$refs.stockTableRef as any).getCheckboxRecords();
  if (selectRows.length == 0) {
    VxeMessage('请选择库存', VxeNotifyType.error);
  } else {
    for (const sltEmploy of selectRows) {
      let cnt = orderForm.reagentList.findIndex((a: any) => a.stockId == sltEmploy.id);
      if (cnt > -1) {
        continue;
      }
      let outStock = {
        orderInfoId: orderForm.id,
        stockId: sltEmploy.id,
        reaNo: sltEmploy.reaNo,
        reaNa: sltEmploy.reaNa,
        specModel: sltEmploy.specModel,
        batchNum: sltEmploy.batchNum,
        amount: sltEmploy.quantity,
        applyNum: sltEmploy.quantity,
        unit: sltEmploy.unit,
        costPrice: sltEmploy.price,
        produceDate: sltEmploy.produceDate,
        expiryDate: sltEmploy.expiryDate,
        uniqueCode: sltEmploy.uniqueCode,
        seq: 1
      };
      orderForm.reagentList.push(outStock);
    }
    isStockVisiable.value = false;
  }
}

function deleteReagent(row: any) {
  proxy
    .$confirm('确定删除？', '提示', {
      cancelButtonClass: 'cancel-button',
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    .then(async () => {
      const $table = proxy.$refs.reagentTableRef as any;

      if ($table) {
        let cnt = orderForm.reagentList.findIndex((a: any) => a.stockId == row.stockId);
        if (cnt > -1) {
          await $table.remove(row);
          orderForm.reagentList.splice(cnt, 1);
          VxeMessage('删除成功', VxeNotifyType.success);
        }
      }
    })
    .catch((err: any) => {
      // VxeMessage(err, VxeNotifyType.error);
    });
}
function cancelStockEvent() {
  isStockVisiable.value = false;
}

function handleTypeNodeClick(data: any) {
  searchStockForm.storeCode = data.storeCode;
  searchStockForm.storeName = data.storeName;
  const selectOrgRef: any = proxy.$refs['selectOrgRef'];
  selectOrgRef.blur();
  findReagentStockList();
}

function clearStoreCode() {
  findReagentStockList();
}

/**下拉选中行事件 */
async function SelectRowClick(e) {
  e.aimKeys.forEach((r) => {
    orderForm[r.aimKey] = e.row[r.rowKey];
  });
}
function formatCommon(arr: any, value: any) {
  for (const item of arr) {
    if (item.code == value) {
      return item.name;
    }
  }
}
// 判断申请是否大于库存数
function pdNum(row) {
  if (row.applyNum == 0) {
    VxeMessage('申请数量不能为0!', VxeNotifyType.error);
    row.applyNum = 1;
  }
  if (row.applyNum > row.amount) {
    VxeMessage('申请数量大于库存数量，请重新输入!', VxeNotifyType.error);
    row.applyNum = row.amount;
  }
}
function formatTransType(arr: any, value: any) {
  for (const item of arr) {
    if (item.transferCode == value) {
      return item.transferName;
    }
  }
}

function getStatusClass(row: any) {
  const status = row.orderStatus;
  if (status == '0') {
    return 'text-orange';
  } else if (status == '5') {
    return 'text-green';
  } else if (status == '10') {
    return 'text-orange';
  } else if (status == '15') {
    return 'text-blue';
  } else if (status == '20') {
    return 'text-black';
  }
}
</script>

<style lang="scss" scoped>
#invOrderOutDiv {
  width: 100%;
  height: 100%;

  .bodyContent {
    height: calc(100% - 60px);
    // 右侧保存按钮
    .saveBtn {
      //float: right;
      margin: 0px 30px;
    }
    // 附加按钮间距
    .button-blue {
      margin: 5px 0 5px 5px;
    }
    .button-red {
      margin: 5px 0 5px 5px;
    }

    // 机构表格
    :deep(.vxe-table--render-default) {
      height: 100%;
    }
    :deep(.vxe-table--render-wrapper) {
      height: 100%;
      background-color: $base-white;
    }
    .tableBox {
      height: calc(100% - 40px);
    }
    .tableBoBox {
      height: calc(100% - 40px);
    }
    .horizontalLine {
      background-color: $base-white;
    }

    .searchform {
      padding: 10px 0 0 10px;

      :deep(.vxe-form--item) {
        margin-right: 30px;
      }
    }

    .searchform .vxe-input {
      --el-input-width: 120px;
    }

    .searchform .vxe-select {
      --el-select-width: 120px;
    }
    .form-input-m {
      .el-input {
        width: 150px;
      }

      .vxe-input {
        width: 150px !important;
      }
    }
  }
}
</style>
